<!--********************************************************************
* Copyright© 2000 - 2018 SuperMap Software Co.Ltd. All rights reserved.
*********************************************************************-->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title data-i18n="resources.title_editFeature"></title>
    <script type="text/javascript" src="../../dist/openlayers/include-openlayers.js"></script>
    <style>
        .editPane {
            position: absolute;
            right: 65px;
            top: 8px;
            text-align: center;
            background: #FFF;
            z-index: 1000;
            border-radius: 4px;
        }

        .ol-popup {
            position: absolute;
            background-color: white;
            -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
            filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #cccccc;
            bottom: 12px;
            left: -50px;
            min-width: 120px;
        }

        .ol-popup:after, .ol-popup:before {
            top: 100%;
            border: solid transparent;
            content: " ";
            height: 0;
            width: 0;
            position: absolute;
            pointer-events: none;
        }

        .ol-popup:after {
            border-top-color: white;
            border-width: 10px;
            left: 48px;
            margin-left: -10px;
        }

        .ol-popup:before {
            border-top-color: #cccccc;
            border-width: 11px;
            left: 48px;
            margin-left: -11px;
        }

        .tooltip {
            position: relative;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 4px;
            color: white;
            padding: 4px 8px;
            opacity: 0.7;
            white-space: nowrap;
        }
    </style>
</head>
<body style=" margin: 0;overflow: hidden;background: #fff;width: 100%;height:100%">
<div id="map" style="width: 100%;height:100%"></div>
<div id="popup" class="ol-popup">
    <div id="popup-content"></div>
</div>
<div>
    <div class="panel panel-primary editPane" id="editPane">
        <div class='panel-heading'>
            <h5 class='panel-title text-center' data-i18n="resources.text_editSingle"></h5></div>
        <div class='panel-body content'>
            <input type='button' class='btn btn-default' data-i18n="[value]resources.btn_addMarker"
                   onclick='addMarker()'/>&nbsp;
            <input type='button' class='btn btn-default' data-i18n="[value]resources.btn_undoAdd"
                   onclick='revocationMarker()'/>
            <input type='button' class='btn btn-default' data-i18n="[value]resources.text_input_value_submit"
                   onclick='commit()'/>&nbsp;
            <input type='button' class='btn btn-default' data-i18n="[value]resources.text_input_value_clear"
                   onclick='clearLayer()'/>
        </div>
    </div>
</div>
<script type="text/javascript" include="bootstrap,widgets.alert" src="../js/include-web.js"></script>
<script type="text/javascript">
    var map, id = [], pointFeature, vectorSource, resultLayer, editFeaturesService, alertDiv,
        addPointsSource, addPointsLayer,
        host = window.isLocal ? window.server : "http://support.supermap.com.cn:8090",
        baseUrl = host + "/iserver/services/map-world/rest/maps/World",
        url = host + "/iserver/services/data-world/rest/data",
        container = document.getElementById('popup'),
        content = document.getElementById('popup-content'),
        overlay = new ol.Overlay(({
            element: container,
            autoPan: true,
            autoPanAnimation: {
                duration: 250
            },
            offset: [0, -20]
        })),

        map = new ol.Map({
            target: 'map',
            controls: ol.control.defaults({attributionOptions: {collapsed: false}})
                .extend([new ol.supermap.control.Logo()]),
            view: new ol.View({
                center: [0, 0],
                zoom: 3,
                projection: 'EPSG:4326'
            }),
        });
    var layer = new ol.layer.Tile({
        source: new ol.source.TileSuperMapRest({
            url: baseUrl
        }),
        projection: 'EPSG:4326'
    });
    map.addLayer(layer);

    //创建鼠标操作提示：
    var helpTooltipElement, helpTooltip, isclearPoint;

    createHelpTooltip();

    function createHelpTooltip() {
        if (helpTooltipElement) {
            helpTooltipElement.parentNode.removeChild(helpTooltipElement);
        }
        helpTooltipElement = document.createElement('div');
        helpTooltipElement.className = 'tooltip hidden';
        helpTooltip = new ol.Overlay({
            element: helpTooltipElement,
            offset: [15, 0],
            positioning: 'center-left'
        });
    }

    initFeature();
    loadLayer();

    function loadLayer() {
        //添加查询结果图层
        vectorSource = new ol.source.Vector({
            wrapX: false
        });
        resultLayer = new ol.layer.Vector({
            source: vectorSource,
        });

        //添加点图层
        addPointsSource = new ol.source.Vector({
            wrapX: false
        });
        addPointsLayer = new ol.layer.Vector({
            source: addPointsSource,
        });

        map.addLayer(addPointsLayer);
        map.addLayer(resultLayer);
    }

    editFeaturesService = new ol.supermap.FeatureService(url);

    function initFeature() {
        var polygon = new ol.geom.Polygon([[[118, 20], [120, 20], [120, 50], [-120, 50], [118, 20]]]);
        var featureService = new ol.supermap.FeatureService(url);
        var getFeatureParams = new SuperMap.GetFeaturesByGeometryParameters({
            toIndex: -1,
            datasetNames: ["World:Capitals"],
            geometry: polygon,
            spatialQueryMode: "INTERSECT"
        });
        featureService.getFeaturesByGeometry(getFeatureParams, function (serviceResult) {
            var features = (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features);
            for (var i = 0; i < features.length; i++) {
                features[i].setStyle(new ol.style.Style({
                    image: new ol.style.Icon(({
                        anchor: [0.5, 0.9],
                        src: '../img/markerbig_select.png'
                    }))
                }));
            }

            //避免重复添加图层，只对一个图层进行数据更新操作：
            if (vectorSource.getFeatures().length > 0) {
                vectorSource.clear();
            }
            vectorSource.addFeatures(features);

            map.on('pointermove', pointermoveLinstener);
        });
    }

    function pointermoveLinstener(e) {
        var select = false;
        map.forEachFeatureAtPixel(e.pixel, function (feature) {
            if (feature.getProperties().CAPITAL) {
                map.getTargetElement().style.cursor = 'pointer';
                var contentHTML = feature.getProperties().CAPITAL;
                content.innerHTML = contentHTML;
                overlay.setPosition(feature.getGeometry().getCoordinates());
                map.addOverlay(overlay);
                select = true
            }
        }, {
            hitTolerance: 10
        });
        if (!select) {
            map.getTargetElement().style.cursor = '';
            overlay.setPosition(undefined);
            map.removeOverlay(overlay);
        }
        if (isclearPoint) {
            helpTooltipElement.innerHTML = resources.text_selectMarkerToDelete;
            helpTooltip.setPosition(e.coordinate);
            helpTooltipElement.classList.remove('hidden');
            map.addOverlay(helpTooltip);
        } else {
            helpTooltip.setPosition(undefined);
            helpTooltipElement.classList.add('hidden');
        }
    }

    function addMarker() {
        if (isclearPoint) {
            closeSelectListener();
        }
        widgets.alert.clearAlert();
        var xmax = 120, xmin = 100, ymax = 50, ymin = 20,
            point = [Math.floor(Math.random() * (xmax - xmin + 1) + xmin), Math.floor(Math.random() * (ymax - ymin + 1) + ymin)];
        if (!pointFeature) {
            ceateMarker(point)
        } else {
            addPointsSource.clear();
            ceateMarker(point)
        }

        function ceateMarker(point) {
            pointFeature = new ol.Feature(new ol.geom.Point(point));
            pointFeature.setStyle(new ol.style.Style({
                image: new ol.style.Circle({
                    fill: new ol.style.Fill({
                        color: [255, 0, 0, 0.5]
                    }),
                    stroke: new ol.style.Stroke({
                        color: 'red',
                        width: 2
                    }),
                    radius: 8
                })
            }));
            pointFeature.setProperties({POP: 1, CAPITAL: 'test'});
            //判断添加点图层已添加到地图，避免重复添加图层，只对一个图层进行数据更新操作：
            addPointsSource.addFeature(pointFeature);
            map.getView().animate({
                duration: 850,
                zoom: 5,
                center: point,
            });
        }
    }

    function revocationMarker() {
        if (isclearPoint) {
            closeSelectListener();
        }
        if (pointFeature) {
            addPointsSource.clear();
            pointFeature = null;
        } else {
            widgets.alert.showAlert(resources.msg_noRevocableMarker, false);
        }
    }

    function commit() {
        widgets.alert.clearAlert();
        if (isclearPoint) {
            closeSelectListener();
        }
        if (pointFeature) {
            var addFeatureParams = new SuperMap.EditFeaturesParameters({
                features: pointFeature,
                dataSourceName: "World",
                dataSetName: "Capitals",
                editType: "add",
                returnContent: true
            });
            editFeaturesService.editFeatures(addFeatureParams, function (serviceResult) {
                if (serviceResult.result.succeed) {
                    id.push(serviceResult.result[0]);
                    addPointsSource.clear();
                    vectorSource.clear();
                    pointFeature = null;
                    initFeature();
                    widgets.alert.showAlert(resources.msg_submitSuccess, true);
                }
            });
        } else {
            widgets.alert.showAlert(resources.msg_noMarkerToSubmit, false);
        }
    }

    function clearLayer() {
        widgets.alert.clearAlert();
        isclearPoint = true;
        map.on('click', selectListener);
    }

    function selectListener(e) {
        var deletedId = null;
        map.forEachFeatureAtPixel(e.pixel, function (feature) {
            //只删选中第一个要素：
            if (!deletedId) {
                deletedId = feature.getProperties().ID;
                var deleteParams = new SuperMap.EditFeaturesParameters({
                    dataSourceName: "World",
                    dataSetName: "Capitals",
                    IDs: [deletedId],
                    editType: "delete"
                });

                editFeaturesService.editFeatures(deleteParams, function (serviceResult) {
                    if (serviceResult.result.succeed) {
                        initFeature();
                        vectorSource.clear();
                        isclearPoint = false;
                        closeSelectListener();
                        widgets.alert.showAlert("resources.text_deleteSuccess", true);
                    } else {
                        widgets.alert.showAlert("resources.msg_deleteFailed", false)
                    }
                });
            }
        }, {
            hitTolerance: 1
        });

    }

    function closeSelectListener() {
        isclearPoint = false;
        map.un('click', selectListener);
        helpTooltip.setPosition(undefined);
        map.removeOverlay(helpTooltip);
        helpTooltipElement.classList.add('hidden');
    }

</script>
</body>
</html>